from typing import Dict, Any, Tuple

from models.network_config_model import NetworkConfigModel


class NetworkConfigController:
    """网络配置控制器"""

    def __init__(self, model: NetworkConfigModel):
        self.model = model

    def validate_network_config(self, network_type: str, config_data: Dict[str, Any]) -> Tuple[bool, str]:
        """验证网络配置数据"""
        # 检查必填字段
        if not config_data.get("dhcp", True):
            ip = config_data.get("ip", "").strip()
            mask = config_data.get("mask", "").strip()

            if not ip or not mask:
                return False, f"{'内网' if network_type == 'internal' else '外网'}配置不完整: IP地址和子网掩码是必填项"

            # 验证IP格式
            if not self.model.validate_ip(ip):
                return False, f"{'内网' if network_type == 'internal' else '外网'}IP地址格式无效"

            if not self.model.validate_ip(mask):
                return False, f"{'内网' if network_type == 'internal' else '外网'}子网掩码格式无效"

            # 验证网关
            gateway = config_data.get("gateway", "").strip()
            if gateway and not self.model.validate_ip(gateway):
                return False, f"{'内网' if network_type == 'internal' else '外网'}网关格式无效"

            # 验证DNS
            dns1 = config_data.get("dns1", "").strip()
            if dns1 and not self.model.validate_ip(dns1):
                return False, f"{'内网' if network_type == 'internal' else '外网'}首选DNS格式无效"

            dns2 = config_data.get("dns2", "").strip()
            if dns2 and not self.model.validate_ip(dns2):
                return False, f"{'内网' if network_type == 'internal' else '外网'}备用DNS格式无效"

        return True, ""

    def save_network_config(self, network_type: str, config_data: Dict[str, Any]) -> Tuple[bool, str]:
        """保存网络配置"""
        # 验证配置
        is_valid, error_msg = self.validate_network_config(network_type, config_data)
        if not is_valid:
            return False, error_msg

        # 保存配置
        success = self.model.save_config(network_type, config_data)
        if success:
            return True, f"{'内网' if network_type == 'internal' else '外网'}配置已保存"
        else:
            return False, f"保存{'内网' if network_type == 'internal' else '外网'}配置时出错"

    def get_network_config(self, network_type: str) -> Dict[str, Any]:
        """获取网络配置"""
        return self.model.get_config(network_type)